package club.kynb.mall.application.flow.order;

import club.kynb.mall.application.assembler.ProductAssembler;
import club.kynb.mall.application.context.OrderPreviewContext;
import club.kynb.mall.order.model.dto.ShoppingCartDTO;
import club.kynb.mall.product.api.IProductInfoService;
import club.kynb.mall.product.dto.ProductByParamDTO;
import club.kynb.mall.product.dto.ProductSpuDetailDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.common.web.exception.Errors;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.pizza.util.Checker;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kynb_club@163.com
 * @since 2021/7/5 9:02 下午
 */
@Slf4j
@Component
@AllArgsConstructor
public class BuildProductListFilter implements Filter<OrderPreviewContext> {
    private final IProductInfoService iProductInfoService;

    @Override
    public void doFilter(OrderPreviewContext orderPreviewContext, FilterInvoker<OrderPreviewContext> filterInvoker) {
        log.info("构建产品列表过滤器 start");
        final List<ShoppingCartDTO> checkedList = orderPreviewContext.getCheckedList();
        final List<Long> skuIdList = checkedList.stream()
                .map(shoppingCartDTO -> Long.valueOf(shoppingCartDTO.getSkuId()))
                .collect(Collectors.toList());
        final List<Long> spuIdList = checkedList.stream()
                .map(shoppingCartDTO -> Long.valueOf(shoppingCartDTO.getSpuId()))
                .collect(Collectors.toList());
        final List<ProductSpuDetailDTO> productSpuList = iProductInfoService.listOnSaleByParam(new ProductByParamDTO().setIds(spuIdList));
        Checker.ifNotThrow(checkedList.size() == spuIdList.size(), () -> Errors.SYSTEM.exception("系统异常，购物车内商品与实际商品数量不匹配"));
        //sku过滤处理
        final List<ProductSpuDetailDTO> skuFilteredList = ProductAssembler.skuFilter(productSpuList, skuIdList);
        orderPreviewContext.setFilteredSpuList(skuFilteredList);
        log.info("构建产品列表过滤器 end");
        filterInvoker.invoke(orderPreviewContext);
    }
}
